package com.qhhc.controller;

import com.qhhc.entity.User;
import com.qhhc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        
        Map<String, Object> response = new HashMap<>();
        
        // 查询用户
        User user = userService.getUserByUsername(username);
        
        if (user == null) {
            response.put("success", false);
            response.put("message", "用户名不存在");
            return ResponseEntity.ok(response);
        }
        
        // 验证密码
        if (!password.equals(user.getPassword())) { // 实际应用中应使用加密比对
            response.put("success", false);
            response.put("message", "密码错误");
            return ResponseEntity.ok(response);
        }
        
        // 登录成功，生成token（实际应用中使用JWT等）
        String token = "user_" + user.getUserId() + "_" + System.currentTimeMillis();
        
        response.put("success", true);
        response.put("message", "登录成功");
        response.put("token", token);

        response.put("userId", user.getUserId());
        response.put("username", user.getUsername());
        response.put("nickname", user.getNickname());
        response.put("userType", user.getUserType());
        response.put("email", user.getEmail());
        response.put("phone", user.getPhone());
        response.put("avatar", user.getAvatar());
        response.put("gender", user.getGender());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        
        // 检查用户名是否已存在
        User existingUser = userService.getUserByUsername(user.getUsername());
        if (existingUser != null) {
            response.put("success", false);
            response.put("message", "用户名已存在");
            return ResponseEntity.ok(response);
        }
        
        // 设置默认值
        user.setUserType("0"); // 普通用户
        user.setStatus("0"); // 正常状态
        
        // 保存用户（实际应用中应加密密码）
        int result = userService.insertUser(user);
        
        if (result > 0) {
            response.put("success", true);
            response.put("message", "注册成功");
        } else {
            response.put("success", false);
            response.put("message", "注册失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "退出成功");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 忘记密码
     */
    @PostMapping("/forgot-password")
    public ResponseEntity<Map<String, Object>> forgotPassword(@RequestBody Map<String, String> forgotForm) {
        String email = forgotForm.get("email");
        
        Map<String, Object> response = new HashMap<>();
        
        // 检查邮箱是否存在
        User user = userService.getUserByEmail(email);
        if (user == null) {
            response.put("success", false);
            response.put("message", "该邮箱未注册");
            return ResponseEntity.ok(response);
        }
        
        // 生成重置密码的令牌
        String resetToken = "reset_" + user.getUserId() + "_" + System.currentTimeMillis();
        
        // 模拟发送邮件，实际应用中应该使用邮件服务
        // emailService.sendResetPasswordEmail(user.getEmail(), resetToken);
        
        response.put("success", true);
        response.put("message", "密码重置链接已发送到您的邮箱");
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, String> resetForm) {
        String token = resetForm.get("token");
        String newPassword = resetForm.get("password");
        
        Map<String, Object> response = new HashMap<>();
        
        // 验证令牌
        // 实际应用中应检查令牌是否有效，是否过期
        if (token == null || !token.startsWith("reset_")) {
            response.put("success", false);
            response.put("message", "无效的令牌");
            return ResponseEntity.ok(response);
        }
        
        // 从令牌中提取用户ID
        String[] parts = token.split("_");
        if (parts.length < 2) {
            response.put("success", false);
            response.put("message", "无效的令牌格式");
            return ResponseEntity.ok(response);
        }
        
        Long userId;
        try {
            userId = Long.parseLong(parts[1]);
        } catch (NumberFormatException e) {
            response.put("success", false);
            response.put("message", "无效的用户ID");
            return ResponseEntity.ok(response);
        }
        
        // 更新密码
        int result = userService.resetPassword(userId, newPassword);
        
        if (result > 0) {
            response.put("success", true);
            response.put("message", "密码重置成功");
        } else {
            response.put("success", false);
            response.put("message", "密码重置失败");
        }
        
        return ResponseEntity.ok(response);
    }
} 